import React, { useState } from 'react';
import styled, { css, keyframes } from 'styled-components';

// 定义 keyframes
const slideUp = keyframes`
  to {
    transform: translateY(-100%);
    opacity: 0;
  }
`;

// 增强震动效果的动画
const slideUpNew = keyframes`
  0% {
    transform: translateY(100%);
  }
  30% {
    transform: translateY(-5px) rotate(-2deg) scale(1.05);
  }
  45% {
    transform: translateY(3px) rotate(1deg);
  }
  60% {
    transform: translateY(-2px) rotate(-0.5deg);
  }
  75% {
    transform: translateY(1px) rotate(0.2deg);
  }
  90% {
    transform: translateY(-0.5px) rotate(-0.1deg);
  }
  100% {
    transform: translateY(0) rotate(0);
  }
`;

// 定义样式组件
const NumberContainer = styled.div`
  position: relative;
  width: 500px;
  height: 50px;
  overflow: hidden;
  border: 1px solid #ccc;
  text-align: center;
  line-height: 50px;
  font-size: 24px;
`;

const NumberElement = styled.div<{ $isOld?: boolean; $isNew?: boolean }>`
  position: absolute;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease-in-out;
  
  ${({ $isOld }) =>
    $isOld && css`
      animation: ${slideUp} 0.1s ease-in-out forwards;
    `}
    
  ${({ $isNew }) =>
    $isNew && css`
      transform: translateY(100%);
      animation: ${slideUpNew} 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
    `}
`;

const ChangeButton = styled.button`
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  
  &:hover {
    background-color: #45a049;
  }
`;

const AnimationShake = () => {
  const [number, setNumber] = useState(0);
  const [isChanging, setIsChanging] = useState(false);

  const handleChangeNumber = () => {
    setIsChanging(true);
    setTimeout(() => {
      setNumber((prevNumber) => prevNumber + 1);
      setIsChanging(false);
    }, 300);
  };

  return (
    <div className='flex items-center align-center'>
     <div>
     <NumberContainer>
        {isChanging && <NumberElement $isOld>{number}</NumberElement>}
        <NumberElement $isNew={isChanging}>{isChanging ? number + 1 : number}</NumberElement>
      </NumberContainer>
     </div>
     <div> <ChangeButton onClick={handleChangeNumber}>改变数字</ChangeButton></div>
    </div>
  );
};

export default AnimationShake;